#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: Charlie.Chen
@project: cc_test
@file: celeryconfig.py
@function:
@time: 2022/7/25 18:14
"""
import re
# from gevent import monkey

# monkey.patch_all(thread=False,socket=False)

from celery.schedules import crontab
from datetime import timedelta, datetime
from kombu import Exchange, Queue
from urllib.parse import quote

from server import cfg
from server.celery_app.utils.schedulers import DatabaseScheduler


def get_pro_type(file_path="D:\\pythonProject\\automation323\\server111\\.env"):
    pro_type = None
    try:
        with open(file_path, 'r') as file:
            for line in file:
                match = re.match(r'^\s*PRO_TYPE\s*=\s*(.*)\s*$', line)
                if match:
                    pro_type = match.group(1)
                    break
    except Exception as e:
        pass
    return pro_type


_, mysql_password = re.search('//(.*)@localhost:13306', cfg.CONF.database.connection).group(1).split(':')

# worker_pool = 'gevent'
# worker_concurrency = 4

broker_url = "amqp://admin:{}@rabbitmq-service:5672/".format(quote(cfg.CONF.rabbitmq_pwd))
result_backend = 'db+mysql://automation:{}@localhost:3306/celery-schedule'.format(quote(mysql_password))
task_track_started = True

timezone = 'UTC'
task_serializer = 'json'
result_serializer = 'json'
enable_utc = True
worker_log_format = "%(asctime)s: %(levelname)s/%(processName)s %(message)s"
worker_task_log_format = "%(asctime)s: %(levelname)s/%(processName)s %(task_name)s [%(task_id)s]: %(message)s"

beat_max_loop_interval = 10
beat_dburi = 'mysql+pymysql://automation:{}@localhost:3306/celery-schedule'.format(quote(mysql_password))

worker_max_tasks_per_child = 10
worker_cancel_long_running_tasks_on_connection_loss = True

task_time_limit = 7200
task_reject_on_worker_lost = True
task_acks_late = True

ampcon_otn_task = dict()
ampcon_pro_type = get_pro_type()

ampcon_common_task = {
    "update-db-license-count-task": {
        "task": "beat_update_db_license_count",
        "schedule": timedelta(seconds=cfg.CONF.license_fresh_interval),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "INTERVAL"
        }

    },
    "collect-backup-config-all-task": {
        "task": "beat_collect_backup_config_all",
        "schedule": crontab(day_of_month="*/3", hour=22, minute=0),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "CRONTAB"
        }
    },
    "update-vpn-client-status-task": {
        "task": "beat_update_vpn_client_status",
        "schedule": timedelta(seconds=60),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "INTERVAL"
        }
    },
    "update-cpu-mem-record": {
        "task": "beat_update_cpu_mem_record",
        "schedule": timedelta(seconds=60),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "INTERVAL"
        }
    },
    "update-alarm-logs-read-tag": {
        "task": "beat_update_alarm_logs_read_tag",
        "schedule": timedelta(days=1),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "INTERVAL"
        }
    },
    "check-license-expire-time": {
        "task": "beat_check_license_expire_time",
        "schedule": crontab(hour=0, minute=0),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "CRONTAB"
        }
    },
    "collect-virtual_resource_info": {
        "task": "beat_sync_virtual_resource_info",
        "schedule": timedelta(seconds=60),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "INTERVAL"
        }
    },
    "update-host-info-task": {
        "task": "beat_update_host_info",
        "schedule": timedelta(seconds=60*10),
        "options": {
            "start_time": datetime.now()
        },
        "kwargs": {
            "celery_type": "INTERVAL"
        }
    },
}

if ampcon_pro_type not in ["ampcon-dc", "ampcon-campus"]:
    ampcon_otn_task = {
        "sync-dcp920-device-info": {
            "task": "beat_sync_dcp920_device_info",
            "schedule": timedelta(minutes=5),
            "options": {
                "start_time": datetime.now()
            },
            "kwargs": {
                "celery_type": "INTERVAL"
            }
        },
        "sync-fmt-device-info": {
            "task": "beat_sync_fmt_device_info",
            "schedule": timedelta(minutes=5),
            "options": {
                "start_time": datetime.now()
            },
            "kwargs": {
                "celery_type": "INTERVAL"
            }
        }
    }

imports = (
    "celery_app.normal_task",
    "celery_app.beat_task",
    "celery_app.snmp_trap_task",
    "celery_app.config_distribution_task",
    "ansible_lib.ansible_utils",
    "api.new_config_api",
    "api.new_rma_api",
    "api.new_lifecycle_api",
    "service.upgrade_switch",
    "ansible_deploy_switch",
    "api.new_inventory_api"
)

beat_schedule = {**ampcon_common_task, **ampcon_otn_task}

beat_scheduler = 'utils.schedulers:DatabaseScheduler'

pica8_exchange = Exchange("pica8", type="topic")

task_queues = (
    Queue("pica8_beat_task", pica8_exchange, routing_key="beat_#"),
    Queue("pica8_normal_task", pica8_exchange, routing_key="normal_#"),
    Queue("pica8_deploy_upgrade_task", pica8_exchange, routing_key="start_#"),
    Queue("snmp_trap_alarm", pica8_exchange, routing_key="snmp_trap_#"),
    Queue("config_distribution_task", pica8_exchange, routing_key="config_distribution_#")
)

task_routes = {
    'beat_*': {"queue": "pica8_beat_task"},
    'normal_*': {"queue": "pica8_normal_task"},
    'start_*': {"queue": "pica8_deploy_upgrade_task"},
    'snmp_trap_*': {"queue": "snmp_trap_alarm"},
    'config_distribution_*': {"queue": "config_distribution_task"}
}

task_default_queue = "pica8_normal_task"
task_default_exchange = pica8_exchange
task_default_exchange_type = "topic"
task_default_routing_key = "normal_#"
